import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/db/love_database.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/components/video/video_page_view.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'package:wallpaper/tools/route_animation.dart';
import 'dart:async';

class LoveVideo extends StatefulWidget {
  final String axis;
  const LoveVideo({super.key, required this.axis});

  @override
  State<LoveVideo> createState() => _LoveVideoState();
}

class _LoveVideoState extends State<LoveVideo> {
  List videos = [];

  // 用于管理重新加载数据的定时器
  Timer? _reloadTimer;

  Future<void> getData() async {
    var res =
        await context.read<LoveDatabase>().getAllLove('video', widget.axis);
    setState(() {
      videos = res;
    });
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    // 取消定时器，防止内存泄漏
    _reloadTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final SettingProvider setting = Provider.of<SettingProvider>(context);
    return Scaffold(
      floatingActionButton: SizedBox(
        height: 45,
        width: 45,
        child: FloatingActionButton(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50),
          ),
          child: Icon(Icons.delete, color: Colors.red),
          onPressed: () {
            showCupertinoDialog(
              //点击空白处取消
              barrierDismissible: true,
              context: context,
              builder: (context) {
                return CupertinoAlertDialog(
                  title: Text(S.of(context).s8),
                  content: Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(S.of(context).s9),
                  ),
                  actions: [
                    CupertinoDialogAction(
                      child: Text(S.of(context).s10),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    CupertinoDialogAction(
                      child: Text(S.of(context).s11),
                      onPressed: () {
                        context
                            .read<LoveDatabase>()
                            .removeAllLove('video', widget.axis);
                        setState(() {
                          videos = [];
                        });
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          },
        ),
      ),
      body: videos.isEmpty
          ? Empty()
          : Padding(
              padding: EdgeInsets.all(setting.padding),
              child: CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: SizedBox(
                      height: MediaQuery.of(context).padding.top,
                    ),
                  ),
                  SliverGrid(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: widget.axis == 'horizontal'
                          ? OptionsBase().horizontalColumns(context)
                          : OptionsBase().imageColumns(context),
                      childAspectRatio: widget.axis == 'horizontal' ? 1.7 : 0.7,
                      mainAxisSpacing: setting.padding,
                      crossAxisSpacing: setting.padding,
                    ),
                    delegate: SliverChildBuilderDelegate(
                      childCount: videos.length,
                      (context, index) =>
                          buildItem(context, index, setting.radius),
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget buildItem(context, int index, double radius) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(radius),
      child: GestureDetector(
        onTap: () {
          RouteAnimation().animateRoute(
            context,
            VideoPageView(
              videoList: videos,
              activeIndex: index,
              isLove: true,
              resetGetdata: () {
                // 取消之前的定时器（如果存在）
                _reloadTimer?.cancel();

                // 等待 500 ms，重新获取数据
                _reloadTimer = Timer(Duration(milliseconds: 500), () {
                  // 检查组件是否仍然挂载
                  if (mounted) {
                    getData();
                  }
                });
              },
            ),
          );
        },
        child: Stack(
          alignment: Alignment.bottomLeft,
          children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ImageLoad(imageUrl: videos[index].smallPath)),
            Center(
              child: Icon(Icons.play_circle,
                  color: const Color.fromARGB(173, 255, 255, 255), size: 50),
            ),
            if (videos[index].tags != '')
              Container(
                width: double.infinity,
                padding: EdgeInsets.all(3),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.black.withOpacity(0),
                      Colors.black.withOpacity(1),
                    ],
                  ),
                ),
                child: Text(
                  videos[index].tags,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: TextStyle(color: Colors.white, fontSize: 13),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
